package com.cheifsteam.springframework.beans.factory;

import com.cheifsteam.springframework.beans.BeansException;
import com.cheifsteam.springframework.beans.PropertyValue;
import com.cheifsteam.springframework.beans.PropertyValues;
import com.cheifsteam.springframework.beans.factory.config.BeanDefinition;
import com.cheifsteam.springframework.beans.factory.config.BeanFactoryPostProcessor;
import com.cheifsteam.springframework.core.io.DefaultResourceLoader;
import com.cheifsteam.springframework.core.io.Resource;

import java.io.IOException;
import java.util.Properties;

/**
 * @Author: 屈燃希
 * @Date: 2025/8/7
 * @Version: V1.0
 * @Description:
 */
public class PropertyPlaceholderConfigurer implements BeanFactoryPostProcessor {

    /**
     * Default placeholder prefix: {@value}
     */
    public static final String DEFAULT_PLACEHOLDER_PREFIX = "${";

    /**
     * Default placeholder suffix: {@value}
     */
    public static final String DEFAULT_PLACEHOLDER_SUFFIX = "}";

    private String location;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {


        try {
            DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
            Resource resource = resourceLoader.getResource(location);
            Properties properties = new Properties();
            properties.load(resource.getInputStream());

            String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
            for (String beanDefinitionName : beanDefinitionNames) {
                BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanDefinitionName);

                PropertyValues propertyValues = beanDefinition.getPropertyValues();
                for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {
                    Object value = propertyValue.getValue();
                    if (!(value instanceof String)) {
                        continue;
                    }
                    final String strVal  = (String) value;
                    StringBuilder builder = new StringBuilder();
                    int startIdx = builder.indexOf(DEFAULT_PLACEHOLDER_PREFIX);
                    int endIdx = builder.indexOf(DEFAULT_PLACEHOLDER_SUFFIX);
                    if (startIdx != -1 && endIdx != -1 && startIdx < endIdx) {
                        String propKey =strVal.substring(startIdx+2,endIdx);
                        String propVal = properties.getProperty(propKey);
                        builder.replace(startIdx,endIdx+1,propVal);
                        propertyValues.addPropertyValue(new PropertyValue(propertyValue.getName(),builder.toString()));
                    }

                }
            }
        } catch (IOException e) {
            throw  new BeansException("can not load properties");
        }
    }


    public void setLocation(String location) {
        this.location = location;
    }
}
